import { Service, FileStream } from 'egg';
import * as sendToWormhole from 'stream-wormhole';
import * as UUID from 'uuid';
import * as path from 'path';
/**
 * Base Service
 */
interface IPagination {
  page: number;
  limit: number;
  total: number;
  hasMore: boolean;
}

export default class BaseService extends Service {
  private pageParams: IPagination;
  constructor(ctx) {
    super(ctx);
    this.pageParams = {
      page: Number(this.ctx.query.page) || 1,
      limit: Number(this.ctx.query.limit) || 10,
      total: 0,
      hasMore: true,
    };
  }
  async pagination(model, params): Promise<{ list: any[], pagination: IPagination }> {
    const { limit, page } = this.pageParams;
    const offset: number = limit * (page - 1);
    params.offset = offset;
    params.limit = limit;
    const { rows, count } = await model.findAndCountAll(params);
    const hasMore: boolean = count > (limit * page);
    this.pageParams.total = count;
    this.pageParams.hasMore = hasMore;
    return { list: rows, pagination: this.pageParams };
  }
  // 生成上传文件的名称
  generateUploadFileName(stream: FileStream): string {
    const year = new Date().getFullYear();
    const month = new Date().getMonth() + 1;
    const storageFileName = UUID.v1() + path.extname(stream.filename).toLowerCase();
    const name = `${year}${month}/${storageFileName}`;
    return name;
  }
  /**
   * @description: 上传
   * @param {type}
   * @return:
   */
  async upload(stream: FileStream): Promise<{url: string, name: string}> {
    const { ctx } = this;
    try {
      const name = this.generateUploadFileName(stream);
      const result = await ctx.alioss.put(name, stream);
      return {
        url: result.url,
        name: result.name,
      };
    } catch (err) {
      await sendToWormhole(stream);
      throw err;
    }
  }
}
